﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RSEngine.Core;
using RSEngine.Math;

namespace RSRenderer.OptimizedGeometry
{
    abstract public class Mesh : OGeometry
    {

        #region Variables

        public Vertex[] Vertices;
        public int[] Indices;

        public AxisAlignedBox BoundingBox = AxisAlignedBox.Invalid;

        #endregion

        #region Constructor

        public Mesh(MeshGeometry geometry)
        {
            Vertices = geometry.Vertices.ToArray<Vertex>();
            Indices = geometry.Indices.ToArray<int>();

            for (int index = 0; index < Vertices.Length; index++)
                TransformVertex(geometry.WorldTransform, ref Vertices[index]);

            UpdateBoundingBox();
        }

        #endregion

        #region TransformVertex

        private void TransformVertex(Matrix4 worldTransform, ref Vertex vertex)
        {
            // full transformation
            vertex.Coordinate = worldTransform * vertex.Coordinate;

            // No translation
            vertex.Normal.x = (worldTransform.M00 * vertex.Normal.x) + (worldTransform.M01 * vertex.Normal.y) + (worldTransform.M02 * vertex.Normal.z);
            vertex.Normal.y = (worldTransform.M10 * vertex.Normal.x) + (worldTransform.M11 * vertex.Normal.y) + (worldTransform.M12 * vertex.Normal.z);
            vertex.Normal.z = (worldTransform.M20 * vertex.Normal.x) + (worldTransform.M21 * vertex.Normal.y) + (worldTransform.M22 * vertex.Normal.z);
        }

        #endregion

        #region UpdateBoundingBox

        private void UpdateBoundingBox()
        {
            for (int index = 0; index < Vertices.Length; index++)
                BoundingBox.Merge(Vertices[index].Coordinate);
        }

        #endregion

    }
}
